﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;

namespace OrchardFork.Framework.Mvc.Routes
{
    public class RoutePublisher : IRoutePublisher
    {
        private readonly RouteCollection _routeCollection;

        public RoutePublisher(RouteCollection routeCollection)
        {
            _routeCollection = routeCollection;

        }

        public void Publish(IEnumerable<RouteDescriptor> routes)
        {
            var routesArray = routes
                .OrderByDescending(r => r.Priority)
                .ToArray();
            var preloading = new RouteCollection();
            foreach (var routeDescriptor in routesArray)
            {
                preloading.Add(routeDescriptor.Name, routeDescriptor.Route);
            }


            using (_routeCollection.GetWriteLock())
            {

                // new routes are added
                foreach (var routeDescriptor in routesArray)
                {
                    _routeCollection.Add(routeDescriptor.Name,routeDescriptor.Route);
                }
            }
        }
    }
}
